package liquidfs.ui.web;

import java.io.*;
import java.net.*;
import java.util.logging.*;

import utility.*;

import liquidfs.*;

import com.sun.net.httpserver.*;

public class WebInterface {
   
   private Application app;
   private HttpServer server;
   private int port;
   private HttpContext indexContext;
  
   private static Logger log = Logger.getLogger("liquidfs.ui.web");
   
   public WebInterface (Application app) {
      
      this.app = app;
      this.port = app.getConfiguration().getWebPort();
      InetSocketAddress address = new InetSocketAddress(port);
      
      try {
         
         // Create the server and set up its handlers
         server = HttpServer.create(address, port);
         //server.createContext("/", new BufferedHandler(app, getResource ("web/index.html")));
         server.createContext("/", new DirectHandler(app, "web/index.html"));
         server.createContext("/style.css", new DirectHandler(app, "web/style.css"));
         server.createContext("/jquery.js", new BufferedHandler(app, getResource ("web/jquery-1.7.2.min.js")));
         server.createContext("/queues", new QueuesHandler(app));
      }
      catch (IOException e) {
         throw new UserUncheckedException("Unable to start web interface: " + e.getLocalizedMessage());
      }
   }
   
   public void start () {
      log.info("Starting HTTP Server on " + server.getAddress().toString());
      server.start();
   }
   
   public void stop () {
      server.stop(0);
   }
   
   public int getPort () {
      return this.port;
   }
   
   private InputStream getResource (String path) throws IOException {
      if (Application.isJar())
         return this.getClass().getResourceAsStream("/" + path);
      else
         return new FileInputStream(path);
   }
}
